class MyPage extends BaseEditWithTree {
    constructor(getTreeUrl, changeCatalogueUrl, fetchNodeUrl, saveNodeUrl, deleteNodeUrl, returnUrl) {
        super(getTreeUrl, changeCatalogueUrl, fetchNodeUrl, saveNodeUrl, deleteNodeUrl, returnUrl);
    }
    GetNodeData () {
        var item = {};        
        item['departmentId'] = $("#CatalogueId").val();
        item['parentId'] = $("#ParentId").val();
        item['orderNo'] = $.trim($("#OrderNo").val());
        item['departmentName'] = $.trim($("#CatalogueName").val());
        item['description'] = formatNullInputValue($.trim($("#Description").val()));
        item['updatedBy'] = $("#UserId").val();

        return JSON.stringify(item);
    }
    FetchByKey(nodeId) {
        $.ajax({
            type: "GET",
            url: parent.basePath + this.fetchNodeUrl,
            timeout: 30 * 1000,
            data: {'key': nodeId},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done((data) => {
            $("#CatalogueId").val(data.departmentId);            // 部门ID
            $("#ParentId").val(data.parentId);                   // 部门ID
            $("#ParentCatalogueName").val(data.parentName);      // 所属部门
            $("#OrderNo").val(data.orderNo);                     // 部门编码
            $("#CatalogueName").val(data.departmentName);        // 部门
            $("#Description").val(data.description);             // 备注
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(( ) => {
            $("#loading").hide();
        });
    }
    // 新增信息
    InsertNode() {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择一个所属部门。");
            return;
        }
        this.pageStatus = 1; // 设置为新增状态

        // 清空表单内容，准备下一个记录
        this.ClearForm();
        $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：增加");
        let _selectedNodeId = sel === "j1_1" ? 0 : sel;
        let _select_node = $("#" + sel);
        $('#ParentCatalogueName').val(_select_node.attr("fullname"));
        $('#ParentId').val(_selectedNodeId);
        $('#CatalogueId').val("0");

        // 设置焦点
        $("#OrderNo").focus();
    }
    // 保存数据
    SaveNode() {
        // 设置为无效状态
        if (parseInt(this.pageStatus) === -1) {
            ShowErrorMessagePanel("对不起，不能修改系统初始信息。");
            return false;
        }
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        let _obj = $("#" + sel);
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择部门。");
            return false;
        }

        if (!$("#form_data").valid())
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + this.saveNodeUrl,
            timeout: 30 * 1000,
            data: this.GetNodeData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done((data) => {
            if (parseInt(data) > 0) {
                switch (parseInt(this.pageStatus)) {
                    case 0: //  编辑
                        // 修改路径名
                        let _fullname = $.trim($("#ParentCatalogueName").val()) + " → " + $.trim($("#CatalogueName").val());
                        _obj.attr("fullname", _fullname);
                        ref.rename_node(_obj, $.trim($("#CatalogueName").val())); // 修改节点文字
                        break;
                    case 1: // 新增
                        $("#CatalogueId").val(data);
                        //let _obj = $("#" + sel);
                        // 增加树形节点
                        ref.create_node(_obj, this.NewNode());
                        ref.load_node(_obj);
                        ref.open_node(_obj);
                        // 取消当前选择点
                        ref.deselect_node(_obj);
                        // 选择该结点
                        let _newNode = $("#" + data);
                        ref.select_node(_newNode);
                        this.pageSstatus = 0; // 设置为编辑状态
                        break;
                }
                ShowSuccessMessagePanel('保存成功。');
            }
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    // 删除
    DeleteNode() {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择部门。");
            return false;
        }
        if (sel === "j1_1") {
            ShowErrorMessagePanel("不能删除根节点。");
            return false;
        }
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', () => {
            let instance = {};
            instance['departmentId'] = $("#CatalogueId").val();
            instance['deletedBy'] = $("#UserId").val();
            $.ajax({
                type: "POST",
                url: parent.basePath + this.deleteNodeUrl,
                timeout: 30 * 1000,
                data: JSON.stringify(instance),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                }
            }).done((data) => {
                if (data > 0) {
                    // 删除树形节点
                    let sel = $.jstree.reference('treeContent').get_selected()[0];
                    $.jstree.reference('treeContent').delete_node(sel);

                    // 删除成功后，清空右侧表单内容
                    this.ClearForm();
                    $("#OperatingMode").html("");
                    $('#ParentCatalogueName').val("");

                    $('#CatalogueId').val("0");
                    ShowSuccessMessagePanel("删除成功。");
                }
            }).fail((data) => {
                ajaxError(data, 1);
            }).always(( ) => {
            });
        });
    }
}

var _Instance = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    _Instance = new MyPage('/master/department/tree.html',
            '/master/department/changeParentCatalogue.html',
            '/master/department/fetchByKey.html',
            '/master/department/save.html',
            '/master/department/delete.html',
            '/master/employee/list.html?flag=1');

    _Instance.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    var h = $(window).height();
    var w = $(window).width();

    $("#treeArea").css({height: h - 110});
    $("#grid__wrapper").css({width: w - 8 - 275});
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _OrderNo: "required",
            _DepartmentName: "required"
        },
        messages: {
            _OrderNo: "请填写部门编码。",
            _DepartmentName: "请填写部门。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: parent.showErrors  //使用自定义的错误显示方法
    });
});
